/**
 *	react code split 之 异步加载组件
 * */
import React, { Component } from 'react';
import { Spin } from 'antd';
import { JSLoad, JSFailLoad, dataLoad } from './LoadIcon';

/**
 *	异步加载组件 嵌套 spin
 * ChildComponent接收 Promise () => import()
 * withSpin default true
 * */
const LazyComponent = (ChildComponent, withSpin = true) =>
  class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        Dom: null,
        tip: null,
        loadingIcon: JSLoad,
        loading: true
      };
      this.load();
    }

    load = () => {
      ChildComponent()
        .then(dom => {
          this.setState({
            loading: false,
            Dom: dom.default ? dom.default : null
          });
          const { lazyComponentDidLoad } = this.props;
          // 组件加载完成 回调
          if (dom.default && typeof lazyComponentDidLoad === 'function') {
            lazyComponentDidLoad(dom.default.name);
          }
        })
        .catch(() => {
          this.setState({
            loadingIcon: JSFailLoad,
            tip: '组件加载失败'
          });
        });
    };

    // 显示 loading
    showLoading = (tip = null) => {
      this.setState({ loading: true, loadingIcon: dataLoad, tip });
    };

    // 隐藏 loading
    hideLoading = () => {
      this.setState({ loading: false });
    };

    render() {
      const { Dom, loading, loadingIcon, tip } = this.state;
      if (withSpin) {
        return (
          <Spin spinning={loading} indicator={loadingIcon} tip={tip}>
            {Dom ? (
              <Dom showLoading={this.showLoading} hideLoading={this.hideLoading} {...this.props} />
            ) : null}
          </Spin>
        );
      }
      return Dom ? <Dom {...this.props} /> : null;
    }
  };

export default LazyComponent;
